unit Updater;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient, IdHTTP, ShellAPI, URLMon, ExtCtrls, DB, DBTables;

type
  TfrmUpdate = class(TForm)
    lblUpdateIntro: TLabel;
    btnContinue: TButton;
    btnSkipUpdate: TButton;
    lblUpdateStatus: TLabel;
    mChangelog: TMemo;
    procedure btnSkipUpdateClick(Sender: TObject);
    procedure btnContinueClick(Sender: TObject);
    function DownloadFile(SourceFile, DestFile: string): Boolean;
    procedure FormShow(Sender: TObject);
  public
    { Public declarations }
  end;

var
  frmUpdate: TfrmUpdate;
  lvCountdown: integer;

implementation

{$R *.dfm}

function TfrmUpdate.DownloadFile(SourceFile, DestFile: string): Boolean;
begin
  try
    Result := UrlDownloadToFile(nil, PChar(SourceFile), PChar(DestFile), 0, nil) = 0;
  except
    Result := False;
  end;
end;

procedure TfrmUpdate.FormShow(Sender: TObject);
begin
  DeleteFile('changelog.txt');
  DownloadFile('http://www.moonpunchstudios.co.uk/software/gipm/changelog.txt/?', GetCurrentDir + '\' + 'changelog.txt');

  if FileExists('changelog.txt') then
    mChangelog.Lines.LoadFromFile('changelog.txt')
  else
    mChangelog.Lines.Add('No changelog found.')
end;

procedure TfrmUpdate.btnContinueClick(Sender: TObject);
const
  SourceFile = 'http://www.moonpunchstudios.co.uk/software/gipm/update.exe';
var
  lvCountDown: integer;
  DestFile:    string;
begin
  DestFile := GetCurrentDir + '\' + 'update.exe';

  lblUpdateStatus.Caption := 'Downloading update, please wait...';

  if DownloadFile(SourceFile, DestFile) then
  begin
    lvCountDown := 5;

    while lvCountDown > 0 do
    begin
      lblUpdateStatus.Caption := 'Download successful, restarting GIPM in ' + IntToStr(lvCountDown) + ' seconds';
      Application.ProcessMessages;
      dec(lvCountDown, 1);
      sleep(1000);
    end;

    // Start the updater
    ShellExecute(Application.Handle, PChar('open'), PChar(DestFile),
      PChar(''), nil, SW_NORMAL);

    // Terminate now 'older' version
    Application.Terminate;
  end
  else
    ShowMessage('Error downloading update, please check your connection.' + #13#10 + #13#10 +
                'Starting GIPM - No changes have been made.');
end;

procedure TfrmUpdate.btnSkipUpdateClick(Sender: TObject);
begin
  self.Close;
end;

end.
